{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "将已有的图片名称读取存放到txt中保存"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "#paths=['coco2014','Stanford','vehicleplate']\n",
    "paths=['VOC2019']\n",
    "f=open('train_all.txt', 'w')\n",
    "for path in paths:\n",
    "    p=os.path.abspath(path)+'/JPEGImages'\n",
    "    filenames=os.listdir(p)\n",
    "    for filename in filenames:\n",
    "        im_path=p+'/'+filename\n",
    "        print(im_path)\n",
    "        f.write(im_path+'\\n')\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"1.下载17种花卉数据图片，每40张分类到一个文件夹中\n",
    "下载地址：http://www.robots.ox.ac.uk/~vgg/data/flowers/17/\n",
    "\"\"\"\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "n=0\n",
    "label=0\n",
    "with open(\"images/jpg/files.txt\",\"r\") as f:\n",
    "    for line in f.readlines():\n",
    "        if n < 40:\n",
    "            n=n+1\n",
    "        else:\n",
    "            label=label+1\n",
    "            n=0\n",
    "        path = 'images/jpg/'+ line.replace(\"\\n\", \"\")\n",
    "        path2 ='images/train/'+str(label)+'/'\n",
    "        if not os.path.exists(path2):\n",
    "            os.makedirs(path2)\n",
    "        shutil.move( path , path2+line.replace(\"\\n\", \"\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "286 123 286 123\n",
      "预测结果:\n",
      "[6 2 6 6 3 4 4 0 3 7 6 2 0 6 8 9 8 7 4 4 0 4 0 2 4 4 7 8 4 4 2 9 1 4 6 6 5\n",
      " 0 2 7 9 8 4 2 4 6 0 8 7 4 7 7 8 3 5 3 2 7 3 4 8 3 2 0 6 4 0 2 3 4 7 4 6 8\n",
      " 4 4 6 4 3 3 0 8 7 0 7 9 4 8 1 7 1 6 0 2 6 0 7 4 7 4 3 6 5 7 3 2 3 4 9 9 7\n",
      " 1 2 6 5 6 6 8 2 4 8 9 2]\n",
      "算法评价:\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.58      0.64      0.61        11\n",
      "           1       0.25      0.11      0.15         9\n",
      "           2       0.43      0.43      0.43        14\n",
      "           3       0.17      0.33      0.22         6\n",
      "           4       0.16      0.40      0.23        10\n",
      "           5       0.00      0.00      0.00        15\n",
      "           6       0.47      0.62      0.53        13\n",
      "           7       0.38      0.38      0.38        16\n",
      "           8       0.25      0.21      0.23        14\n",
      "           9       0.71      0.33      0.45        15\n",
      "\n",
      "    accuracy                           0.34       123\n",
      "   macro avg       0.34      0.34      0.32       123\n",
      "weighted avg       0.35      0.34      0.33       123\n",
      "\n",
      "第二张图的字典型分类报告:\n",
      "precision :      0.25\n",
      "recall    :      0.11\n",
      "f1-score  :      0.15\n",
      "support   :      9.00\n",
      "images/train/8/image_0350.jpg\n",
      "6\n",
      "images/train/4/image_0181.jpg\n",
      "2\n",
      "images/train/6/image_0271.jpg\n",
      "6\n",
      "images/train/7/image_0290.jpg\n",
      "6\n",
      "images/train/2/image_0082.jpg\n",
      "3\n",
      "images/train/2/image_0086.jpg\n",
      "4\n",
      "images/train/1/image_0068.jpg\n",
      "4\n",
      "images/train/0/image_0030.jpg\n",
      "0\n",
      "images/train/8/image_0348.jpg\n",
      "3\n",
      "images/train/8/image_0330.jpg\n",
      "7\n"
     ]
    }
   ],
   "source": [
    "\"\"\"2.朴素贝叶斯分类识别\n",
    "\n",
    "将400张图像按照训练集为70%，测试集为30%的比例随机划分，\n",
    "再获取每张图像的像素直方图，（这里后面替换为你的提取特征的方法）\n",
    "根据像素的特征分布情况进行图像分类分析。\n",
    "\"\"\"\n",
    "\n",
    "# -*- coding: utf-8 -*-\n",
    "import os\n",
    "import cv2\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import confusion_matrix, classification_report\n",
    "\n",
    "#----------------------------------------------------------------------------------\n",
    "# 第一步 切分训练集和测试集\n",
    "#----------------------------------------------------------------------------------\n",
    "\n",
    "X = [] #定义图像名称\n",
    "Y = [] #定义图像分类类标\n",
    "#Z = [] #定义图像像素\n",
    "\n",
    "for i in range(0, 10):\n",
    "    #遍历文件夹，读取图片\n",
    "    for f in os.listdir(\"images/train/%s\" % i):\n",
    "        #获取图像名称\n",
    "        X.append(\"images/train/\" +str(i) + \"/\" + str(f))\n",
    "        #获取图像类标即为文件夹名称\n",
    "        Y.append(i)\n",
    "\n",
    "X = np.array(X)\n",
    "Y = np.array(Y)\n",
    "\n",
    "#随机率为100% 选取其中的30%作为测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, Y,test_size=0.3, random_state=1)\n",
    "\n",
    "print(len(X_train), len(X_test), len(y_train), len(y_test))\n",
    "\n",
    "#----------------------------------------------------------------------------------\n",
    "# 第二步 图像读取及转换为像素直方图\n",
    "#----------------------------------------------------------------------------------\n",
    "\n",
    "#训练集\n",
    "XX_train = []\n",
    "for i in X_train:\n",
    "    #读取图像\n",
    "    #print i\n",
    "    image = cv2.imread(i)\n",
    "    \n",
    "    #图像像素大小一致\n",
    "    img = cv2.resize(image, (256,256),interpolation=cv2.INTER_CUBIC)\n",
    "\n",
    "    #计算图像直方图并存储至X数组\n",
    "    hist = cv2.calcHist([img], [0,1], None,[256,256], [0.0,255.0,0.0,255.0])\n",
    "\n",
    "    XX_train.append(((hist/255).flatten()))\n",
    "\n",
    "#测试集\n",
    "XX_test = []\n",
    "for i in X_test:\n",
    "    #读取图像\n",
    "    #print i\n",
    "    image = cv2.imread(i)\n",
    "    \n",
    "    #图像像素大小一致\n",
    "    img = cv2.resize(image, (256,256),interpolation=cv2.INTER_CUBIC)\n",
    "\n",
    "    #计算图像直方图并存储至X数组\n",
    "    hist = cv2.calcHist([img], [0,1], None,[256,256], [0.0,255.0,0.0,255.0])\n",
    "\n",
    "    XX_test.append(((hist/255).flatten()))\n",
    "\n",
    "#----------------------------------------------------------------------------------\n",
    "# 第三步 基于朴素贝叶斯的图像分类处理\n",
    "#----------------------------------------------------------------------------------\n",
    "\n",
    "from sklearn.naive_bayes import BernoulliNB\n",
    "# 使用训练集训练模型\n",
    "clf = BernoulliNB().fit(XX_train, y_train)#伯努利贝叶斯分类器\n",
    "predictions_labels = clf.predict(XX_test)\n",
    "\n",
    "# 使用测试集预测结果\n",
    "print(u'预测结果:')\n",
    "print(predictions_labels)\n",
    "# 生成文本型分类报告\n",
    "print(u'算法评价:')#算法评价准确率（Precision）、召回率（Recall）和F值（F1-score）\n",
    "print((classification_report(y_test, predictions_labels)))\n",
    "# 生成字典型分类报告\n",
    "report = classification_report(y_test, predictions_labels, output_dict=True)\n",
    "print(u'第二张图的字典型分类报告:')\n",
    "for key, value in report[\"1\"].items():\n",
    "    print(f\"{key:10s}:{value:10.2f}\")\n",
    "    \n",
    "#输出前10张图片及预测结果\n",
    "k = 0\n",
    "while k<10:\n",
    "    #读取图像\n",
    "    print(X_test[k])\n",
    "    image = cv2.imread(X_test[k])\n",
    "    print(predictions_labels[k])\n",
    "    #显示图像\n",
    "    cv2.imshow(\"img\", image)\n",
    "    cv2.waitKey(0)\n",
    "    cv2.destroyAllWindows()\n",
    "    k = k + 1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
